package liuch.socketdemov2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Map;

/**
 * @author: liuchenhui
 * @create: 2019-10-10 11:47
 **/
public class ClientHandler implements Runnable {

    private Map<String, PrintWriter> allOut;

    private Socket socket;

    public ClientHandler(Socket socket, Map<String, PrintWriter> allOut) {
        this.socket = socket;
        this.allOut = allOut;
    }

    @Override
    public void run() {
        PrintWriter printWriter = null;
        try {
            OutputStream outputStream = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(outputStream, "UTF-8");
            printWriter = new PrintWriter(osw, true);

            allOut.put(String.valueOf(socket.getInetAddress()), printWriter);
            System.out.println("所有在线的socket：" + allOut.keySet());

            InputStream inputStream = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader br = new BufferedReader(isr);

            String msg = null;
            while ((msg = br.readLine()) != null) {
                sendMsg(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            allOut.remove(String.valueOf(socket.getInetAddress()));
            System.out.println("清除下线的socket后，在线的socket：" + allOut.keySet());
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private synchronized void sendMsg(String msg) {
        System.out.println(msg);
        String ip = msg.split(",")[0];
        PrintWriter p = allOut.get(ip);
        if (p != null) {
            p.println(msg.split(",")[1]);
        }
    }
}
